package com.yanfan.zutai.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.core.text.Convert;
import com.yanfan.system.service.ISysUserService;
import com.yanfan.zutai.domain.BDeviceWarn;
import com.yanfan.zutai.domain.BWeiXin;
import com.yanfan.zutai.domain.BWeiXinUser;
import com.yanfan.zutai.mapper.BWeiXinMapper;
import com.yanfan.zutai.service.IBWeiXinService;
import com.yanfan.zutai.service.IBWeiXinUserService;
import com.yanfan.zutai.util.HttpPostAndGetUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 公众号配置Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-11
 */
@Service
public class BWeiXinServiceImpl implements IBWeiXinService {
    @Autowired
    private BWeiXinMapper bWeiXinMapper;
    @Autowired
    private IBWeiXinUserService bWeiXinUserService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询公众号配置
     *
     * @param id 公众号配置主键
     * @return 公众号配置
     */
    @Override
    public BWeiXin selectBWeiXinById(Long id) {
        return bWeiXinMapper.selectBWeiXinById(id);
    }

    /**
     * 查询公众号配置列表
     *
     * @param bWeiXin 公众号配置
     * @return 公众号配置
     */
    @Override
    public List<BWeiXin> selectBWeiXinList(BWeiXin bWeiXin) {
        return bWeiXinMapper.selectBWeiXinList(bWeiXin);
    }

    /**
     * 新增公众号配置
     *
     * @param bWeiXin 公众号配置
     * @return 结果
     */
    @Override
    public int insertBWeiXin(BWeiXin bWeiXin) {
        return bWeiXinMapper.insertBWeiXin(bWeiXin);
    }

    /**
     * 修改公众号配置
     *
     * @param bWeiXin 公众号配置
     * @return 结果
     */
    @Override
    public int updateBWeiXin(BWeiXin bWeiXin) {
        return bWeiXinMapper.updateBWeiXin(bWeiXin);
    }

    /**
     * 批量删除公众号配置
     *
     * @param ids 需要删除的公众号配置主键
     * @return 结果
     */
    @Override
    public int deleteBWeiXinByIds(Long[] ids) {
        return bWeiXinMapper.deleteBWeiXinByIds(ids);
    }

    /**
     * 删除公众号配置信息
     *
     * @param id 公众号配置主键
     * @return 结果
     */
    @Override
    public int deleteBWeiXinById(Long id) {
        return bWeiXinMapper.deleteBWeiXinById(id);
    }

    @Override
    public String getToken() {
        BWeiXin bWeiXin = new BWeiXin();
        String token = "";
        List<BWeiXin> bWeiXins = bWeiXinMapper.selectBWeiXinList(bWeiXin);
        if (bWeiXins.size() > 0) {
            token = bWeiXins.get(0).getAccessToken();
        }
        return token;
    }

    @Override
    public void renovateToken() {
        BWeiXin bWeiXin = new BWeiXin();
        List<BWeiXin> bWeiXins = bWeiXinMapper.selectBWeiXinList(bWeiXin);
        if (bWeiXins.size() > 0) {
            bWeiXin = bWeiXins.get(0);
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("grant_type", "client_credential"));
            params.add(new BasicNameValuePair("appid", bWeiXin.getAppId()));
            params.add(new BasicNameValuePair("secret", bWeiXin.getSecret()));
            String string = HttpPostAndGetUtil.doGet(url, params, "", "");
            JSONObject jsonObject = JSONObject.parseObject(string, JSONObject.class);
            if (jsonObject.get("access_token") != null) {
                bWeiXin.setAccessToken(jsonObject.get("access_token").toString());
                bWeiXin.setUpdateTime(new Date());
                bWeiXinMapper.updateBWeiXin(bWeiXin);
            }
        }
    }

    @Override
    public void sendMsg(BDeviceWarn bDeviceWarn) {
        SysUser sysUser = sysUserService.selectUserByUserName(bDeviceWarn.getUpdateBy());
        if (sysUser == null) {
            return;
        }
        if (sysUser.getDeptId() == null) {
            return;
        }
        BWeiXinUser bWeiXinUser = new BWeiXinUser();
        bWeiXinUser.setUserName("-" + sysUser.getDeptId().toString());// 查询某一个部门的所有用户
        bWeiXinUser.setSubscribe(1);
        List<BWeiXinUser> bWeiXinUsers = bWeiXinUserService.selectBWeiXinUserList(bWeiXinUser);
        for (int i = 0; i < bWeiXinUsers.size(); i++) {
            String openId = bWeiXinUsers.get(i).getOpenId();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + this.getToken();
            Map<String, Object> map = new HashMap<>();
            map.put("touser", openId);
            map.put("template_id", this.getTemplateId());
            // 小程序跳转
//            Map<String,Object> miniprogram=new HashMap<>();
//            miniprogram.put("appid","wxbd3869622a9315b5");
//            miniprogram.put("pagepath","pages/overview/overview");
//            map.put("miniprogram",miniprogram);
            map.put("topcolor", "#FF0000");// 红色

            Map<String, Object> data = new HashMap<>();

            Map<String, String> childData01 = new HashMap<>();
            childData01.put("value", StrUtil.sub(bDeviceWarn.getWarnMessage(), 0, 20));
            childData01.put("color", "#173177");
            data.put("thing5", childData01);

            Map<String, String> childData02 = new HashMap<>();
            childData02.put("value", bDeviceWarn.getDeviceMac());
            childData02.put("color", "#173177");
            data.put("number12", childData02);

            Map<String, String> childData03 = new HashMap<>();
            childData03.put("value", StrUtil.sub(bDeviceWarn.getDeviceName(), 0, 20));
            childData03.put("color", "#173177");
            data.put("thing2", childData03);

            Map<String, String> childData05 = new HashMap<>();
            childData05.put("value", DateUtil.now());
            childData05.put("color", "#173177");
            data.put("time4", childData05);

            Map<String, String> childData06 = new HashMap<>();
            childData06.put("value", StrUtil.sub(bDeviceWarn.getAddress(), 0, 20));
            childData06.put("color", "#173177");
            data.put("thing14", childData06);
            map.put("data", data);
            System.out.println("公众号推送:" + JSON.toJSONString(map));
            String string = HttpPostAndGetUtil.doPost(url, JSON.toJSONString(map), "", "");
            System.out.println("公众号响应：" + string);
            JSONObject jsonObject = JSONObject.parseObject(string, JSONObject.class);
            if (jsonObject.get("errcode") != null && Convert.toInt(jsonObject.get("errcode")) == 4001) {
                this.renovateToken();
            }
        }
    }

    @Override
    public String getTemplateId() {
        BWeiXin bWeiXin = new BWeiXin();
        String templateId = "";
        List<BWeiXin> bWeiXins = bWeiXinMapper.selectBWeiXinList(bWeiXin);
        if (bWeiXins.size() > 0) {
            templateId = bWeiXins.get(0).getTemplateId();
        }
        return templateId;
    }
}
